package com.le.tester.javaThink.fifth.chapter14_StreamingProgramming;

import java.io.RandomAccessFile;

/**
 * 描述：读写随机访问文件
 */
public class UsingRandomAccessFile {

    static String file = "E:\\L.info\\L.Application\\L.Tester\\src\\main\\java\\com\\le\\tester\\java8\\doc\\rtest.dat";

    public static void display() {
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
            for (int i = 0; i < 7; i++) {
                System.out.println("Value " + i + ": " + randomAccessFile.readDouble());

                System.out.println(randomAccessFile.readUTF());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")) {
            for (int i = 0; i < 7; i++) {
                randomAccessFile.writeDouble(i * 1.414);
                randomAccessFile.writeUTF("the end of the file");
            }
            randomAccessFile.close();
            display();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) {
            rf.seek(5 * 8);
            rf.writeDouble(47.0001);
            rf.close();
            display();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
